package com.imyuanma.qingyun.common.util;

import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.constants.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * web工具类
 *
 * @author wangjy
 * @date 2022/07/09 20:58:52
 */
public class WebUtil {

    private static final Logger logger = LoggerFactory.getLogger(WebUtil.class);

    /**
     * 判断请求是否为ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        if (request.getHeader("accept") != null && request.getHeader("accept").contains("application/json")) {
            return true;
        }
        if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest")) {
            return true;
        }
        return false;
    }

    /**
     * 写入结果到响应流
     *
     * @param response 响应
     * @param result   返回结果
     */
    public static void write2Response(HttpServletResponse response, Result result) {
        if (result != null) {
            write2Response(response, JsonUtil.toJson(result));
        }
    }

    /**
     * 写入结果到响应流
     *
     * @param response 响应
     * @param content  返回内容
     */
    public static void write2Response(HttpServletResponse response, String content) {
        response.setCharacterEncoding(CommonConstants.CHARSET);//编码
        response.setContentType("application/json; charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(content);
        } catch (IOException e) {
            logger.error("[写入响应结果] 响应流写入异常", e);
        } catch (Exception e) {
            logger.error("[写入响应结果] 异常处理过程中发生异常!!!", e);
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {
                logger.error("[写入响应结果] 关闭PrintWriter异常", e);
            }
        }
    }
}
